home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14371 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  69 lines

  1. Newsgroups: comp.lang.c,comp.unix.programmer
  2. Path: news.uunet.ca!wildcan!sq!msb
  3. From: msb@sq.com (Mark Brader)
  4. Subject: Re: Q: '\n' character
  5. Message-ID: <1996Apr14.015303.23020@sq.com>
  6. Organization: SoftQuad Inc., Toronto, Canada
  7. References: <4kj66f$k0o@ren.cei.net> <1996Apr11.192937.25676@sq.com> <829396473snz@genesis.demon.co.uk>
  8. Date: Sun, 14 Apr 1996 01:53:03 GMT
  9.  
  10. > > Instead use:
  11. > >
  12. > >    len = strlen (buffer);
  13. > >    if (len > 0 && buffer[len-1] == '\n') buffer[len-1] = '\0';
  14. > >
  15. > > Both tests in the "if" are necessary.
  16. > Not exactly true. fgets() can never place a zero length string in the
  17. > buffer.
  18.  
  19. It can if there's a null character at the start of the line in the
  20. input.  (One thing you give up by using fgets() is the ability to
  21. do anything with useful text that follows a null character on the input
  22. line, but at least you should avoid making out-of-bounds array references
  23. if there is one.)
  24.  
  25. Demonstration:
  26.  
  27.     #include <stdio.h>
  28.     #include <assert.h>
  29.     
  30.     main()
  31.     {
  32.         FILE *fin, *fout;
  33.         char buf[64];
  34.     
  35.         fout = fopen ("temp", "w");
  36.         assert (fout != NULL);
  37.     
  38.         putc ('\0', fout);
  39.         fprintf (fout, "Hello world\n");
  40.         fclose (fout);
  41.     
  42.         fin = fopen ("temp", "r");
  43.         assert (fin != NULL);
  44.         assert (fgets (buf, sizeof buf, fin) == buf);
  45.     
  46.         printf ("length %d, first byte %d\n", strlen (buf), buf[0]);
  47.         printf ("buf as string ``%s'', buf+1 as string ``%s''\n",
  48.             buf, buf+1);
  49.         
  50.         fclose (fin);
  51.         remove ("temp");
  52.         return 0;
  53.     }
  54.  
  55. On this system, the output is:
  56.  
  57.     length 0, first byte 0
  58.     buf as string ``'', buf+1 as string ``Hello world
  59.     ''
  60.  
  61. -- 
  62. Mark Brader          "Sir, your composure baffles me.  A single counter-
  63. msb@sq.com            example refutes a conjecture as effectively as ten.
  64. SoftQuad Inc.         ... Hands up!  You have to surrender."
  65. Toronto                                               -- Imre Lakatos
  66.  
  67. My text in this article is in the public domain.
  68.